import numpy as np
import matplotlib.pyplot as plt


# 定义函数
def f(x):
    return x ** 2


# 导数
def df(x):
    return 2 * x


# 梯度下降参数
lr = 0.1
# 迭代次数
n_iterations = 10
# 初始值
x1 = 2.5

# 梯度下降算法
for i in range(n_iterations):
    gradient = df(x1)
    x1 = x1 - lr * gradient

# 绘制原始函数
x = np.linspace(-3, 3, 100)

y = f(x)
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='f(x)=x^2')

# 绘制梯度下降过程中x 的位置
x_history = []
y_history = []

# 重新初始化x1,用于演示
x1 = np.random.uniform(-3, 3)
for i in range(n_iterations):
    gradient = df(x1)
    x1 = x1 - lr * gradient
    x_history.append(x1)
    y_history.append(f(x1))
    plt.scatter(x1, f(x1), color='red')

# 绘制梯度下降路径
plt.plot(x_history, y_history, label='Gradient Descent', color='red')

# 设置图形
plt.legend()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Function and Gradient Descent Path')
plt.grid(True)
plt.show()
